<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\controller\Admin;

class Content extends Admin {

	public function _initialize() {
		parent::_initialize();
		//$this->getContentMenu();
		$this->showmode = $showmode = $this->request->param('showmode');
		$this->root_id = $root_id = $this->request->param('root_id');
		$rootInfo = get_category($root_id);
		if(empty(get_category($root_id))){
			$this->root_id = $root_id = 0;
		}
		
		$this->category_id = $category_id = $this->request->param('category_id');
		$this->categoryInfo = $categoryInfo = get_category($category_id);
		if(empty($categoryInfo)){
			$this->category_id = $category_id = 0;
		}
		
		if($category_id == 0)
		{
			if($root_id == 0)
			{
				$this->model_id = $model_id = $this->request->param('model_id');
			}else{
				$this->category_id = $category_id = $root_id;
				$this->categoryInfo = $categoryInfo = $rootInfo;
				$this->model_id = $model_id = $rootInfo['model_id'];
			}
		}else{
			$this->model_id = $model_id = $categoryInfo['model_id'];
		}
		
		$list = db('Model')->column('*', 'id');
		if (empty($list[$model_id])) {
			$this->root_id = 0;
			$this->category_id = 0;
			$this->model_id = 0;
			//return $this->error("无此模型！");
		} else {
			$this->modelInfo = $list[$model_id];
			$this->model = M($this->modelInfo['name']);
		}
		
		$this->getCategoryMenu2($this->root_id);

		$this->assign('model_id', $model_id);
		$this->assign('category_id', $category_id);
		//$this->assign('model_list', $list);
		$this->assign('root_id', ''.$root_id);
		$this->assign('showmode', $showmode);
		$this->assign('keyword', $this->request->param('keyword'));
		$this->setMeta("内容管理");
	}

	protected function getCategoryMenu1() {

		//$map  = array('status' => array('gt', -1));
		//$list = db('Category')->where($map)->order('sort asc,id asc')->column('*', 'id');
		$list = get_category_list_tree("");

		if (!empty($list)) {
			$tree = new \com\Tree();
			$list = $tree->toFormatTree($list);
		}

		foreach($list as $key=>$item){
			if ('admin/content/index' == $this->url && input('category_id') == $item['id']) {
				$item['style'] = "active";
			}else{
				$item['style'] = "";
			}
			$item['url']   = "admin/content/index?model_id=" . $item['model_id']."&category_id=".$item['id'];
			$item['title'] =  $item['title_show'] ; $item['level_show'].$item['title'] ;
			$item['icon']  = $item['icon'] ? $item['icon'] : 'file';
			$menu[]         = $item;
		}

		if (!empty($menu)) {
			$this->assign('extend_menu', array('内容管理' => $menu));
		}

	}

	protected function getCategoryMenu2($root_id) {
		//if($root_id != 0){
			$list = get_category_root_tree($root_id);
		//}else{
			//$list = get_category_list_tree("");
		//}

		if (!empty($list)) {
			$this->assign('category_menu', array('内容管理' => $list));
		}
	}

	protected function getCurUrl() {
		return url('admin/content/index',array('model_id' => $this->modelInfo['id'],'category_id' => $this->category_id));
	}

	/**
	 * 内容列表
	 * @return [html] [页面内容]
	 * @author molong <ycgpp@126.com>
	 */
	public function index() {
		if ($this->model_id == 0 || $this->showmode != 1) {
			return $this->fetch("content/main");
		} 
		/*if ($this->root_id != 0  && $this->showmode != 1) {
			return $this->fetch("content/main");
		} */

		if ($this->modelInfo['list_grid'] == '') {
			return $this->error("列表定义不正确！", url('admin/model/edit', array('id' => $this->modelInfo['id'])));
		}
		$grid_list = get_grid_list($this->modelInfo['list_grid']);
		$order     = "id desc";
		$map       = $this->buildMap();
		$field     = array_filter($grid_list['fields']);

		//$list = $this->model->where($map)->order($order)->paginate($this->modelInfo['list_row']);
		$list = $this->model->where($map)->order($order)->paginate($this->modelInfo['list_row'],false,['path'=>"javascript:showPage('".$this->getCurUrl()."?showmode=1&page=[PAGE]');",]);
//echo implode(" ",$map);
//exit("lsyer");

		$data = array(
			'grid' => $grid_list,
			'list' => $list,
			'page' => $list->render(),
		);
		if ($this->modelInfo['template_list']) {
			$template = 'content/' . $this->modelInfo['template_list'];
		} else {
			$template = 'content/index';
		}
		$this->assign($data);
		if ($this->category_id != 0) {
			$this->setMeta($this->categoryInfo['title'] . "列表");
		} else{
			$this->setMeta($this->modelInfo['title'] . "列表");
		}
		return $this->fetch($template);
	}

	/**
	 * 内容添加
	 * @author molong <ycgpp@126.com>
	 */
	public function add() {
		if (IS_POST) {
			$result = $this->model->save($this->param);
			if ($result) {
				//记录行为
				action_log('add_content', 'content', $result, session('auth_user.uid'));
				return $this->success("添加成功！", url('admin/content/index', array('model_id' => $this->modelInfo['id'], 'root_id' => $this->root_id, 'category_id' => $this->category_id)));
			} else {
				return $this->error($this->model->getError(), url('admin/content/add', array('model_id' => $this->modelInfo['id'])));
			}
		} else {
			$info = array(
				'model_id' => $this->modelInfo['id'],
			);
			$data = array(
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			if ($this->modelInfo['template_add']) {
				$template = 'content/' . $this->modelInfo['template_add'];
			} else {
				$template = 'content/edit';
			}
			$this->assign($data);
			$this->setMeta("添加" . $this->modelInfo['title']);
			return $this->fetch($template);
		}
	}

	/**
	 * 内容修改
	 * @author molong <ycgpp@126.com>
	 */
	public function edit($id) {
		if (IS_POST) {
			$result = $this->model->save($this->param, array('id'=> $id));
			if ($result !== false) {
				//记录行为
				action_log('update_content', 'content', $result, session('auth_user.uid'));
				return $this->success("更新成功！", url('admin/content/index', array('model_id' => $this->modelInfo['id'],'root_id'=> $this->root_id,'category_id'=> $this->category_id)));
			} else {
				return $this->error($this->model->getError(), url('admin/content/edit', array('model_id' => $this->modelInfo['id'], 'id' => $id)));
			}
		} else {
			if (!$id) {
				return $this->error("非法操作！");
			}
			$info = $this->model->find($id);
			if (!$info) {
				return $this->error($this->model->getError());
			}
			$info['model_id'] = $this->modelInfo['id'];
			$data             = array(
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			if ($this->modelInfo['template_edit']) {
				$template = 'content/' . $this->modelInfo['template_edit'];
			} else {
				$template = 'content/edit';
			}
			$this->assign($data);
			$this->setMeta("编辑" . $this->modelInfo['title']);
			return $this->fetch($template);
		}
	}

	/**
	 * 内容删除
	 * @author molong <ycgpp@126.com>
	 */
	public function del() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			$this->assign('operation_status', 'warning');
			//return $this->error("非法操作！");
		}

		$map['id'] = array('IN', $id);
		$result    = $this->model->where($map)->delete();

		if (false !== $result) {
			//记录行为
			action_log('delete_content', 'content', $result, session('auth_user.uid'));
			$this->assign('operation_status', 'success');
			//return $this->success("删除成功！", url('admin/content/index', array('model_id' => $this->modelInfo['id'],'root_id'=> $this->root_id,'category_id'=> $this->category_id)));
		} else {
			$this->assign('operation_status', 'error');
			//return $this->error("删除失败！");
		}

		return $this->index();
	}

	/**
	 * 设置状态
	 * @author molong <ycgpp@126.com>
	 */
	public function status($id, $status) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('status', $status);
		if (false !== $result) {
			$this->assign('operation_status', 'success');
			//return $this->success("操作成功！");
		} else {
			$this->assign('operation_status', 'error');
			//return $this->error("操作失败！！");
		}

		return $this->index();
	}

	/**
	 * 设置置顶
	 * @author molong <ycgpp@126.com>
	 */
	public function settop($id, $is_top) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('is_top', $is_top);

		if (false !== $result) {
			$this->assign('operation_status', 'success');
			//return $this->success("操作成功！", $this->getCurUrl()."?page=".$this->request->param('page'));
		} else {
			$this->assign('operation_status', 'error');
			//return $this->error("操作失败！！", $this->getCurUrl()."?page=".$this->request->param('page'));
		}

		return $this->index();
	}

	/**
	 * 获取字段信息
	 * @return array 字段数组
	 * @author molong <ycgpp@126.com>
	 */
	protected function getField() {
		$field_group = parse_config_attr($this->modelInfo['attribute_group']);

		$map['model_id'] = $this->modelInfo['id'];
		if ($this->request->action() == 'add') {
			$map['is_show'] = array('in', array('1', '2'));
		} elseif ($this->request->action() == 'edit') {
			$map['is_show'] = array('in', array('1', '3'));
		}

		//获得数组的第一条数组
		//$rows    = model('Attribute')->getFieldlist($map, 'id');
		$rows    = model('Attribute')->getFieldlist2($map, 'id', $this->root_id);
		if (!empty($rows)) {
			foreach ($rows as $key => $value) {
				$list[$value['group_id']][] = $value;
			}
			foreach ($field_group as $key => $value) {
				$fields[$value] = isset($list[$key]) ? $list[$key] : array();
			}
		}else{
			$fields = array();
		}
		return $fields;
	}

	/**
	 * 创建搜索
	 * @return [array] [查询条件]
	 */
	protected function buildMap() {
		$map  = array();
		$data = $this->request->param();
		foreach ($data as $key => $value) {
			if ($value) {
				if ($key == 'keyword') {
					$map['title'] = array("LIKE", "%$value%");
				} elseif ($key == 'category') {
					$map['category_id'] = $value;
				} elseif ($key == 'create_time') {
					$map['create_time'] = array('BETWEEN', array(strtotime($value[0]), strtotime($value[1])));
				} else {
					$map[$key] = $value;
				}
			}
		}
		if (isset($map['showmode'])) {
			if (isset($map['is_top'])) {
				unset($map['is_top']);
			}
			if (isset($map['id'])) {
				unset($map['id']);
			}
			if (isset($map['status'])) {
				unset($map['status']);
			}
			unset($map['showmode']);
		}
		if (isset($map['page'])) {
			unset($map['page']);
		}
		if (isset($map['root_id'])) {
			unset($map['root_id']);
		}
		if (isset($map['model_id'])) {
			unset($map['model_id']);
		}
		$this->assign($data);
		return $map;
	}

	/**
	 * 检测需要动态判断的文档类目有关的权限
	 *
	 * @return boolean|null
	 *      返回true则表示当前访问有权限
	 *      返回false则表示当前访问无权限
	 *      返回null，则会进入checkRule根据节点授权判断权限
	 *
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	protected function checkDynamic() {
		$model_id = $this->request->param('model_id');
		if (IS_ROOT) {
			return true; //管理员允许访问任何页面
		}
		$models = model('AuthGroup')->getAuthModels(session('user_auth.uid'));
		if (!$model_id) {
			return false;
		} elseif (in_array($model_id, $models)) {
			//返回null继续判断操作权限
			return null;
		} else {
			return false; //无权限
		}
		return false;
	}
}
